package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"pet-manager/cache"
	"pet-manager/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	img := c.PostForm("img")
	if name == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	article := models.Article{
		Model: gorm.Model{},
		Name:  name,
		Img:   img,
	}
	models.DB.Create(&article)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	office := (page - 1) * size
	var count int64
	models.DB.Model(&models.Article{}).Count(&count)

	var article models.Article
	redis_key := "list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(office).Limit(size).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count":   count,
			"article": article,
		},
	})
	return
}
